package com.rlyy.basic.resolver.argument;

import com.rlyy.common.param.Request;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Parameter;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;

/**
 * @author yuanqinglong
 * @since 2020/7/20 13:37
 */
@Component
public class EntityMethodArgumentResolver implements MyHandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(Parameter parameter) {
        boolean isNotCollection = !Collection.class.isAssignableFrom(parameter.getType());
        boolean isNotMap = !Map.class.isAssignableFrom(parameter.getType());
        boolean isEntity = !BeanUtils.isSimpleProperty(parameter.getType())
                && isNotCollection && isNotMap;
        return isEntity && !BeanUtils.isSimpleProperty(parameter.getType());
    }

    @Override
    public Object resolveArgument(Parameter parameter, Request fullRequest) throws Exception {
        if (Request.class.isAssignableFrom(parameter.getType())) {
            return fullRequest;
        }
        return Optional.ofNullable(fullRequest.getData()).map(d -> d.toJavaObject(parameter.getType())).orElse(null);
    }

}
